package me.firstapp.service.shop.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.shop.Category;
import me.firstapp.module.shop.Product;
import me.firstapp.module.shop.ProductSkuRelation;
import me.firstapp.module.shop.Sku;
import me.firstapp.repository.shop.CategoryRepository;
import me.firstapp.repository.shop.ProductRepository;
import me.firstapp.repository.shop.ProductSkuRelationRepository;
import me.firstapp.repository.shop.SkuRepository;
import me.firstapp.service.shop.ProductService;

@Service
public class ProductServiceImpl implements ProductService {

	@Autowired
	private ProductRepository productRepository;

	@Autowired
	private CategoryRepository categoryRepository;

	@Autowired
	private ProductSkuRelationRepository productSkuRelationRepository;

	@Autowired
	private SkuRepository skuRepository;

	@Override
	public Page<Product> findProductPage(Integer pageNo, Integer pageSize, Long categoryId, Integer disable,
			Long apiClientId) {
		return productRepository.findProductPage(pageNo, pageSize, categoryId, disable, apiClientId);
	}

	@Override
	public Product findProductById(Long productId, Long apiClientId) {
		if (productId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品id");
		}
		return productRepository.findProductById(productId, apiClientId);
	}

	@Override
	public Page<Product> findProductPageByParams(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType, Date startTime, Date endTime, Long apiClientId) {
		return productRepository.findProductPageByParams(pageNo, pageSize, searchParams, sortParam, sortType, startTime,
				endTime, apiClientId);
	}

	@Override
	public Product addProduct(Long categoryId, String listImage, String smallImage, String imges, String name,
			String summary, String detail, String deliver, Double deliverFee, Integer sort, Long apiClientId) {
		if (categoryId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "品类id");
		}
		if (StrUtils.isNULL(listImage)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "列表图片");
		}
		if (StrUtils.isNULL(smallImage)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "小图片");
		}
		if (StrUtils.isNULL(name)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品名称");
		}
		if (StrUtils.isNULL(summary)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品简介");
		}
		if (StrUtils.isNULL(detail)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品详情");
		}
		if (StrUtils.isNULL(deliver)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "配送方式");
		}
		if (deliverFee == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "运费");
		}
		if (sort == null) {
			sort = 0;
		}
		Category category = (Category) categoryRepository.findCategoryById(categoryId, apiClientId);
		if (category == null) {
			throw new ServiceException(StatusHouse.CATEGORY_NOT_FOUND);
		}
		Product product = productRepository.findProductByName(name, apiClientId);
		if (product != null) {
			throw new ServiceException(StatusHouse.PRDT_NAME_IS_EXIST);
		}
		product = new Product();
		product.setAddTime(new Date());
		product.setCategory(category);
		product.setCollectCounts(0L);
		product.setDeliver(deliver);
		product.setDeliverFee(deliverFee);
		product.setDetail(detail);
		product.setDisable(0);
		product.setImages(imges);
		product.setListImage(listImage);
		product.setName(name);
		product.setReplyCounts(0L);
		product.setSmallImage(smallImage);
		product.setSort(sort);
		product.setSummary(summary);
		product.setViewCounts(0L);
		product.setApiClientId(apiClientId);

		productRepository.save(product);
		return product;
	}

	@Override
	public Product updateProduct(Long productId, Long categoryId, String listImage, String smallImage, String images,
			String name, String summary, String detail, String deliver, Double deliverFee, Integer sort,
			Integer disable, Long apiClientId) {
		if (productId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品id");
		}
		Product product = (Product) productRepository.findProductById(productId, apiClientId);
		if (product == null) {
			throw new ServiceException(StatusHouse.PRODUCT_NOT_EXIST);
		}
		// 不更新上下架状态的时候，判断商品是否属于上架状态
		if (disable == null) {
			if (product.getDisable() == 1) {
				throw new ServiceException(StatusHouse.PRDT_IS_SALLING);
			}
		}
		if (categoryId != null) {
			Category category = (Category) categoryRepository.findCategoryById(categoryId, apiClientId);
			if (category == null) {
				throw new ServiceException(StatusHouse.CATEGORY_NOT_FOUND);
			}
			product.setCategory(category);
		}
		if (StrUtils.isNotNULL(listImage)) {
			product.setListImage(listImage);
		}
		if (StrUtils.isNotNULL(smallImage)) {
			product.setSmallImage(smallImage);
		}
		if (StrUtils.isNotNULL(images)) {
			product.setImages(images);
		}
		if (StrUtils.isNotNULL(name)) {
			if (!name.equals(product.getName())) {
				Product _product = productRepository.findProductByName(name, apiClientId);
				if (_product != null) {
					throw new ServiceException(StatusHouse.PRDT_NAME_IS_EXIST);
				}
			}
			product.setName(name);
		}
		if (StrUtils.isNotNULL(summary)) {
			product.setSummary(summary);
		}
		if (StrUtils.isNotNULL(detail)) {
			product.setDetail(detail);
		}
		if (StrUtils.isNotNULL(deliver)) {
			product.setDeliver(deliver);
		}
		if (deliverFee != null) {
			product.setDeliverFee(deliverFee);
		}
		if (sort != null) {
			product.setSort(sort);
		}

		// 上下架处理
		if (disable != null) {
			if (disable == 1) {
				// 检查属性关系是否维护
				List<ProductSkuRelation> rels = productSkuRelationRepository
						.findProductSkuRelationsByProductId(productId, null, apiClientId);
				if (rels == null || rels.isEmpty()) {
					throw new ServiceException(StatusHouse.PRODUCT_SKU_REL_NOT_SET);
				}
				// 检查是否有默认属性关系
				List<ProductSkuRelation> _rels = productSkuRelationRepository
						.findProductSkuRelationsByProductId(productId, 1, apiClientId);
				if (_rels == null || _rels.isEmpty()) {
					throw new ServiceException(StatusHouse.PRODUCT_SKU_REL_NOT_SET_DEFAULT);
				}
			}
			product.setDisable(disable);
		}

		productRepository.update(product);
		return product;
	}

	@Override
	public void deleteProducts(String ids, Long apiClientId) {
		if (StrUtils.isNULL(ids)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品id");
		}
		if (!ids.contains(",")) {
			Product product = (Product) productRepository.findProductById(Long.valueOf(ids), apiClientId);
			if (product == null) {
				throw new ServiceException(StatusHouse.PRODUCT_NOT_EXIST);
			}
			if (product.getDisable() == 1) {
				throw new ServiceException(StatusHouse.PRDT_IS_SALLING);
			}
			productRepository.deleteById(Long.valueOf(ids));

			// 删除属性
			List<Sku> skus = skuRepository.findSkusByProductId(product.getId(), apiClientId);
			Long[] skuIds = new Long[skus.size()];
			for (int i = 0; i < skus.size(); i++) {
				skuIds[i] = skus.get(i).getId();
			}
			skuRepository.delete(skuIds);

			// 删除属性关系
			List<ProductSkuRelation> rels = productSkuRelationRepository
					.findProductSkuRelationsByProductId(product.getId(), null, apiClientId);
			Long[] relIds = new Long[rels.size()];
			for (int i = 0; i < rels.size(); i++) {
				relIds[i] = rels.get(i).getId();
			}
			productSkuRelationRepository.delete(relIds);
		} else {
			String[] _ids = ids.split(",");
			Long[] _ids_ = new Long[_ids.length];
			for (int i = 0; i < _ids.length; i++) {
				_ids_[i] = Long.valueOf(_ids[i]);
			}
			for (int i = 0; i < _ids_.length; i++) {
				Product product = (Product) productRepository.findProductById(_ids_[i], apiClientId);
				if (product == null) {
					throw new ServiceException(StatusHouse.ONE_OR_MORE_PRODUCT_NOT_EXIST);
				}
				if (product.getDisable() == 1) {
					throw new ServiceException(StatusHouse.ONE_OR_MORE_PRDT_IS_SALLING);
				}
				productRepository.deleteById(_ids_[i]);

				// 删除属性
				List<Sku> skus = skuRepository.findSkusByProductId(product.getId(), apiClientId);
				Long[] skuIds = new Long[skus.size()];
				for (int j = 0; j < skus.size(); j++) {
					skuIds[j] = skus.get(j).getId();
				}
				skuRepository.delete(skuIds);

				// 删除属性关系
				List<ProductSkuRelation> rels = productSkuRelationRepository
						.findProductSkuRelationsByProductId(product.getId(), null, apiClientId);
				Long[] relIds = new Long[rels.size()];
				for (int k = 0; k < rels.size(); k++) {
					relIds[k] = rels.get(k).getId();
				}
				productSkuRelationRepository.delete(relIds);
			}
		}
	}

	@Override
	public List<Product> findProducts(Integer disable, Long apiClientId) {
		return productRepository.findProducts(disable, apiClientId);
	}

}
